//
// Created by xiaofoo.
//

#include "EpicCommonCmd.h"

EpicCommonCmd::EpicCommonCmd(const char *cmdName) {
  EpicCmdMgr *cmd_mgr_singleton = EpicCmdMgr::getInstance();

  cmd_mgr_singleton->addCmdMap(cmdName, this);
//  std::cout << "#### 1key: " << cmdName << std::endl;
//  std::cout << "#### 1ptr: " << this << std::endl;

  TclInterpController *interp_singleton = TclInterpController::getInstance();

  Tcl_CreateObjCommand(interp_singleton->interp(), cmdName, run, nullptr,
                       nullptr);
}

EpicCommonCmd::~EpicCommonCmd() {}

int EpicCommonCmd::run(ClientData clientData, Tcl_Interp *interp, int argc,
                        Tcl_Obj *const *argv) {
  EpicCmdMgr *cmd_mgr_singleton = EpicCmdMgr::getInstance();
  std::unordered_map<std::string, EpicCommonCmd *> cmd_map =
      cmd_mgr_singleton->getCmdMap();

  char *cmd_name = Tcl_GetString(argv[0]);

  std::unordered_map<std::string, EpicCommonCmd *>::const_iterator got =
      cmd_map.find(cmd_name);
  int result = TCL_ERROR;
  if (got != cmd_map.end()) {
    EpicCommonCmd *cmd = got->second;
//    std::cout << "#### ptr: " << cmd << std::endl;
//    std::cout << "#### key: " << got->first << std::endl;
    cmd->preExec(clientData, interp, argc, argv);
    result = cmd->exec(clientData, interp, argc, argv);
    cmd->postExec(clientData, interp, argc, argv);
  }
  return result;
}

void EpicCommonCmd::preExec(ClientData clientData, Tcl_Interp *interp,
                             int argc, Tcl_Obj *const *argv) {}

int EpicCommonCmd::exec(ClientData clientData, Tcl_Interp *interp, int argc,
                         Tcl_Obj *const *argv) {
  return 0;
}

void EpicCommonCmd::postExec(ClientData clientData, Tcl_Interp *interp,
                              int argc, Tcl_Obj *const *argv) {}
